package com.example.health.ui.activity

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.content.*
import android.content.pm.PackageManager
import android.location.LocationManager
import android.os.*
import android.support.annotation.RequiresApi
import android.support.v4.app.ActivityCompat
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.*
import cn.jpush.android.api.JPushInterface
import com.example.health.R
import com.example.health.adapter.ContactAdapter
import com.example.health.bean.Contact
import com.example.health.bean.MsgPush
import com.example.health.db.SQLiteUtil
import com.example.health.mode.PurchaseData
import com.example.health.mode.PurchaseInfo
import com.example.health.mode.ShopData
import com.example.health.ui.MyAppliction
import com.example.health.ui.fragment.*
import com.example.health.ui.widget.LineEditText
import com.example.health.ui.widget.SmoothLayout
import com.example.jpushdemo.ExampleUtil
import com.example.jpushdemo.LocalBroadcastManager
import com.google.gson.Gson
import com.iflytek.speech.util.DatesUtils
import com.iflytek.speech.util.HttpUtils
import com.iflytek.speech.util.LogUtil
import com.ucloudrtclib.sdkengine.UCloudRtcSdkEnv
import com.ucloudrtclib.sdkengine.define.UCloudRtcSdkMode
import com.urtcdemo.utils.CommonUtils
import com.urtcdemo.utils.PermissionUtils
import com.urtcdemo.utils.ToastUtils
import com.wakeup.mylibrary.bean.*
import com.wakeup.mylibrary.command.CommandManager
import com.wakeup.mylibrary.data.DataParse
import com.wakeup.mylibrary.service.BluetoothService
import com.wakeup.mylibrary.service.BluetoothService.LocalBinder
import com.wakeup.mylibrary.utils.DataHandUtils
import com.wakeup.mylibrary.utils.SPUtils
import kotlinx.android.synthetic.main.activity_home.*
import kotlinx.android.synthetic.main.dialog_addcontact.view.*
import java.io.*
import java.lang.ref.WeakReference
import java.util.*
import android.os.Vibrator as Vibrator1

class HomeActivity : AppCompatActivity() {
    private var vibrator: Vibrator1? = null
    var rid: String? = ""
    private var adapter: ContactAdapter? = null
    private var phone: String = ""
    private val TAG = MainActivity::class.java.simpleName
    private val REQUEST_ENABLE_BT = 1
    private var mBluetoothLeService: BluetoothService? = null
    private val REQUEST_SEARCH = 1

    var mMenuFragment: MenuFragment? = MenuFragment()
    var mShoppingFragment: ShoppingFragment? = ShoppingFragment()
    var mShoppingInfoFragment: ShoppingInfoFragment? = ShoppingInfoFragment()
    var mShoppingResultFragment: ShoppingResultFragment? = ShoppingResultFragment()
    var mContextFragment: ContextFragment? = null
    var mVideoCallFragment: VideoCallFragment? = VideoCallFragment()
    var mPurchaseFragment: PurchaseFragment? = PurchaseFragment()
    var mFragmentManager: FragmentManager? = null
    var contactList: ArrayList<Contact>? = null
    private var mUserId = ""
    private var mRoomid = "13821686815"
    private var mRoomToken = "testoken"
    private var mAppid: String? = ""
    private var mMessageReceiver: MessageReceiver? = null
    private var commandManager: CommandManager? = null
    private var dataPasrse: DataParse? = null
    private var address: String? = null
    private var progressBar: ProgressBar? = null
    private var isBleUpdate = false
    var addContactDialog: Dialog? = null

    private var mSecretNumber = 0
    private val MIN_CLICK_INTERVAL: Long = 700
    private var mLastClickTime: Long = 0

    //var temptoastText = myToast.view.findViewById<TextView>(R.id.toastText)
    companion object {
        var isForeground: Boolean = false
        const val MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION"
        const val KEY_TITLE = "title"
        const val KEY_MESSAGE = "message"
        const val KEY_EXTRAS = "extras"
    }

    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_home)
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
        adapter = ContactAdapter(this)
        initUCloudRtcSdk()
        requestPermissions()
        registerMessageReceiver() // used for receive msg
        initView()
        initListener()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            // initBLE()
        }
        vibrator = getSystemService(Context.VIBRATOR_SERVICE) as android.os.Vibrator
        progressBar = findViewById(R.id.progressBar)

        Thread(Runnable {
            Log.e(TAG, "JPushInterface Init")
            JPushInterface.init(applicationContext)
            rid = JPushInterface.getRegistrationID(applicationContext)
            Log.d("aaa", "rid:" + rid)
            if (!rid?.isEmpty()!!) {
                //  MainControlBoard.getInstance().Sqlite3_WriteDBConfig("RegistrationID",rid);
            }
        }).start()

        hideBottomUIMenu()

        BtStatus.setOnClickListener({
            val intent = Intent(this@HomeActivity, DeviceScanActivity::class.java)
            startActivityForResult(intent, REQUEST_SEARCH)
        })
    }

    protected fun hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            val v = this.window.decorView
            v.systemUiVisibility = View.GONE
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            val decorView = window.decorView
            val uiOptions = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                    //          | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                    or View.SYSTEM_UI_FLAG_IMMERSIVE)
            decorView.systemUiVisibility = uiOptions
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
        }
    }

    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    private fun initBLE() {
        isBLESupported()

        //开启蓝牙
        if (!isBLEEnabled()) {
            showBLEDialog()
        }

        //6.0以上开启定位
        val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                //showGPSDisabledAlertToUser()
            }
        }

        //启动蓝牙服务
        val gattServiceIntent = Intent(this, BluetoothService::class.java)
        bindService(gattServiceIntent, mServiceConnection, Context.BIND_AUTO_CREATE)

        commandManager = CommandManager.getInstance(this)

        dataPasrse = DataParse.getInstance()
    }

    /**
     * 是否支持蓝牙
     */
    fun isBLESupported() {
        if (!packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            showToast(R.string.no_ble)
        }
    }

    fun showToast(messageResId: Int) {
        Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show()
    }

    /**
     * 蓝牙是否开启
     *
     * @return
     */
    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    @SuppressLint("MissingPermission")
    fun isBLEEnabled(): Boolean {
        val manager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        val adapter = manager.adapter
        return adapter != null && adapter.isEnabled
    }

    /**
     * 请求开启蓝牙
     */
    fun showBLEDialog() {
        val enableIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
        startActivityForResult(enableIntent, REQUEST_ENABLE_BT)
    }

    //Code to manage Service lifecycle
    private val mServiceConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            mBluetoothLeService = (service as LocalBinder).service
            val temp = mBluetoothLeService
            if (!temp!!.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth")
                return
            }
            Log.e(TAG, "onServiceConnected")
        }

        override fun onServiceDisconnected(name: ComponentName) {
            Log.d(TAG, "onServiceDisconnected")
            mBluetoothLeService = null
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null) {
            return
        }
        if (requestCode == REQUEST_SEARCH && resultCode == Activity.RESULT_OK) {
            address = data.getStringExtra("address")
            val name = data.getStringExtra("name")
            Log.i(TAG, "name: $name\naddress: $address")
            //mTextMessage.setText("name: $name\naddress: $address")
            SPUtils.putString(this@HomeActivity, SPUtils.ADDRESS, address)
        }
    }

    /**
     * 一键测量(一键测量的时间为1分钟，1分钟到后发一个关闭指令，手环会返回数据)
     *
     * @param control 0(关)  1(开)
     */
    open fun oneButtonMeasurement(control: Int) {
        commandManager!!.oneButtonMeasurement(1)
        try {
            Thread.sleep(60000)
        } catch (e: InterruptedException) {
            return;
        }
        commandManager!!.oneButtonMeasurement(0)
    }

    private val mGattUpdateReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            if (BluetoothService.ACTION_GATT_CONNECTED == action) {
                Log.i(TAG, "ACTION_GATT_CONNECTED")
                BtStatus.setText("已连接")
                progressBar!!.visibility = View.GONE
            } else if (BluetoothService.ACTION_GATT_DISCONNECTED == action) {
                Log.i(TAG, "ACTION_GATT_DISCONNECTED")
                BtStatus.setText("未连接")
                progressBar!!.visibility = View.GONE
                tvHeatValue.setText("--")
                tvTempValue.setText("--")
                tvBloodPress.setText("--/--")
                tvBloodOxygen.setText("--")
            } else if (BluetoothService.ACTION_GATT_SERVICES_DISCOVERED == action) {
                Log.i(TAG, "ACTION_GATT_SERVICES_DISCOVERED")
            } else if (BluetoothService.ACTION_DATA_AVAILABLE == action) {
                val txValue = intent.getByteArrayExtra(BluetoothService.EXTRA_DATA)
                Log.d(TAG, "接收的数据：" + DataHandUtils.bytesToHexStr(txValue))
                val datas = DataHandUtils.bytesToArrayList(txValue)
                if (datas.size == 0) {
                    return
                }
                if (datas[0] == 0xAB) {
                    when (datas[4]) {
                        0x91 -> {
                            //电池电量
                            val battery = dataPasrse!!.parseData(datas) as Battery
                            Log.i(TAG, battery.toString())
                        }
                        0x92 -> {
                            //手环信息
//                            bandInfo = dataPasrse!!.parseData(datas) as BandInfo
//                            Log.i(MainActivity.TAG, bandInfo.toString())
//                            Log.i(MainActivity.TAG, "hasContinuousHeart:" + Config.hasContinuousHeart)
//                            if (bandInfo.getBandType() == 0x0B || bandInfo.getBandType() == 0x0D || bandInfo.getBandType() == 0x0E || bandInfo.getBandType() == 0x0F) {
//                                Config.hasContinuousHeart = true
//                            }
                        }
                        0x51 -> when (datas[5]) {
                            0x11 -> {
                                //单机测量 心率数据
                                val heartRateBean = dataPasrse!!.parseData(datas) as HeartRateBean
                                Log.i(TAG, heartRateBean.toString())
                            }
                            0x12 -> {
                                //单机测量 血氧数据
                                val bloodOxygenBean =
                                    dataPasrse!!.parseData(datas) as BloodOxygenBean
                                Log.i(TAG, bloodOxygenBean.toString())
                            }
                            0x14 -> {
                                //单机测量 血压数据
                                val bloodPressureBean =
                                    dataPasrse!!.parseData(datas) as BloodPressureBean
                                Log.i(TAG, bloodPressureBean.toString())
                            }
                            0x08 -> {
                                //当前数据
                                val currentDataBean =
                                    dataPasrse!!.parseData(datas) as CurrentDataBean
                                Log.i(TAG, currentDataBean.toString())
                            }
                            0x20 -> {
                                //返回整点数据
                                val hourlyMeasureDataBean =
                                    dataPasrse!!.parseData(datas) as HourlyMeasureDataBean
                                Log.i(TAG, hourlyMeasureDataBean.toString())
                            }
                            0x21 -> {
                                //返回整点 体温、免疫力数据
                                val bodytempAndMianyiBean =
                                    dataPasrse!!.parseData(datas) as BodytempAndMianyiBean
                                Log.i(TAG, bodytempAndMianyiBean.toString())
                            }
                            0x13 -> {
                                //返回单机测量体温
                                val bodyTempBean = dataPasrse!!.parseData(datas) as BodyTempBean
                                Log.i(TAG, bodyTempBean.toString())
                            }
                            0x18 -> {
                                //返回单机测量免疫力
                                val mianyiBean = dataPasrse!!.parseData(datas) as MianyiBean
                                Log.i(TAG, mianyiBean.toString())
                            }
                        }
                        0x52 -> {
                            //入睡时间记录
                            val sleepData = dataPasrse!!.parseData(datas) as SleepData
                            Log.i(TAG, sleepData.toString())
                        }
                        0x31 -> when (datas[5]) {
                            0x09 -> {
                                //心率（单次）
                                val heartRateBean = dataPasrse!!.parseData(datas) as HeartRateBean
                                Log.i(TAG, heartRateBean.toString())
                            }
                            0x11 -> {
                                //血氧（单次）
                                val bloodOxygenBean =
                                    dataPasrse!!.parseData(datas) as BloodOxygenBean
                                Log.i(TAG, bloodOxygenBean.toString())
                            }
                            0x21 -> {
                                //血压（单次）
                                val bloodPressureBean =
                                    dataPasrse!!.parseData(datas) as BloodPressureBean
                                Log.i(TAG, bloodPressureBean.toString())
                            }
                            0X0A -> {
                                //心率（实时）
                                val heartRateBean1 = dataPasrse!!.parseData(datas) as HeartRateBean
                                Log.i(TAG, heartRateBean1.toString())
                            }
                            0x12 -> {
                                //血氧（实时）
                                val bloodOxygenBean1 =
                                    dataPasrse!!.parseData(datas) as BloodOxygenBean
                                Log.i(TAG, bloodOxygenBean1.toString())
                            }
                            0x22 -> {
                                //血压（实时）
                                val bloodPressureBean1 =
                                    dataPasrse!!.parseData(datas) as BloodPressureBean
                                Log.i(TAG, bloodPressureBean1.toString())
                            }
                            0x81 -> {
                                //单次测量体温
                                val bodyTempBean = dataPasrse!!.parseData(datas) as BodyTempBean
                                Log.i(TAG, bodyTempBean.toString())
                            }
                            0x41 -> {
                                //单次测量免疫力
                                val mianyiBean = dataPasrse!!.parseData(datas) as MianyiBean
                                Log.i(TAG, mianyiBean.toString())
                            }
                        }
                        0x32 -> {
                            //一键测量
                            val oneButtonMeasurementBean =
                                dataPasrse!!.parseData(datas) as OneButtonMeasurementBean

                            tvHeatValue.setText(oneButtonMeasurementBean.getHeartRate().toString())
                            tvTempValue.setText(
                                oneButtonMeasurementBean.getTemperature().toString()
                            )
                            tvBloodPress.setText(
                                oneButtonMeasurementBean.getBloodPressure_h()
                                    .toString() + "/" + oneButtonMeasurementBean.getBloodPressure_l()
                                    .toString()
                            )
                            tvBloodOxygen.setText(
                                oneButtonMeasurementBean.getBloodOxygen().toString()
                            )
                            Log.i(TAG, oneButtonMeasurementBean.toString())
                        }
                        0x84 -> {
                            //连续心率手环 实时心率返回
                            val heartRateBean = dataPasrse!!.parseData(datas) as HeartRateBean
                            Log.i(TAG, heartRateBean.toString())
                        }
                        else -> {
                        }
                    }
                }
            }
        }
    }


    private fun initUCloudRtcSdk() {
        val preferences = getSharedPreferences(
            getString(R.string.app_name),
            Context.MODE_PRIVATE
        )
        mAppid = preferences.getString(CommonUtils.APPID_KEY, CommonUtils.APP_ID)
        UCloudRtcSdkEnv.setMixSupport(preferences.getBoolean(CommonUtils.SDK_SUPPORT_MIX, false))
        UCloudRtcSdkEnv.setLoop(preferences.getBoolean(CommonUtils.SDK_IS_LOOP, true))
        UCloudRtcSdkEnv.setMixFilePath(
            preferences.getString(
                CommonUtils.SDK_MIX_FILE_PATH,
                resources.getString(R.string.mix_file_path)
            )
        )
        UCloudRtcSdkEnv.setLogReport(true)
        val permissions = arrayOf(
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        )
        PermissionUtils.needsPermissions(this, permissions)
        val thread = Thread(CopyMixFileTask(this))
        thread.start()
    }

    internal class CopyMixFileTask(context: AppCompatActivity) : Runnable {

        var context: WeakReference<AppCompatActivity>? = null

        init {
            this.context = WeakReference(context)
        }

        override fun run() {
            if (context != null && context!!.get() != null) {
                val storageFileDir =
                    context!!.get()?.getResources()?.getString(R.string.mix_file_dir)
                val storageFilePath = storageFileDir + File.separator + "dy.mp3"
                val fileStorage = File(storageFilePath)
                var needCopy = false
                if (!fileStorage.exists()) {
                    needCopy = true
                }
                val handler = Handler(Looper.getMainLooper())
                if (needCopy) {
                    val file = File(storageFileDir)
                    if (!file.exists()) {//如果文件夹不存在，则创建新的文件夹
                        file.mkdirs()
                    }
                    readInputStream(
                        storageFilePath,
                        context!!.get()?.getResources()?.openRawResource(R.raw.dy)!!
                    )
                    handler.post {
                        if (UCloudRtcSdkEnv.getApplication() != null) {
                            ToastUtils.shortShow(
                                UCloudRtcSdkEnv.getApplication(),
                                "default mix file copy success"
                            )
                        }
                    }
                } else {
                    //                    handler.post(new Runnable() {
                    //                        @Override
                    //                        public void run() {
                    //                            ToastUtils.shortShow(UCloudRtcSdkEnv.getApplication(),"mix file already exist");
                    //                        }
                    //                    });
                }
                context!!.clear()
                context = null
            }
        }

        /**
         * 读取输入流中的数据写入输出流
         *
         * @param storagePath 目标文件路径
         * @param inputStream 输入流
         */
        fun readInputStream(storagePath: String, inputStream: InputStream) {
            val file = File(storagePath)
            try {
                if (!file.exists()) {
                    // 1.建立通道对象
                    val fos = FileOutputStream(file)
                    // 2.定义存储空间
                    val buffer = ByteArray(1024)
                    // 3.开始读文件
                    var length = 0
                    // 循环从输入流读取buffer字节
                    // 将Buffer中的数据写到outputStream对象中
                    while ((inputStream.read(buffer)) != -1) {
                        length = inputStream.read(buffer)
                        fos.write(buffer, 0, length)
                    }
                    fos.flush()// 刷新缓冲区
                    // 4.关闭流
                    fos.close()
                    inputStream.close()
                }
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            } catch (e: IOException) {
                e.printStackTrace()
            }

        }
    }

    private fun initView() {
        smoothLayout.visibility = View.GONE
        if (mFragmentManager == null) {
            mFragmentManager = supportFragmentManager
        }
        showMenuFragment()
//        if (mMenuFragment == null) {
//            mMenuFragment = MenuFragment()
//        }
//        showFragment(mMenuFragment!!)
    }

    private var currentFragment: Fragment? = null

    /**
     * 展示Fragment
     */
    private fun showFragment(fragment: Fragment) {

        if (currentFragment !== fragment) {
            val transaction = mFragmentManager?.beginTransaction()
            if (currentFragment != null) {
                transaction?.hide(currentFragment!!)
            }
            currentFragment = fragment
            if (!fragment.isAdded) {
                transaction?.add(R.id.frameLayout, fragment)?.show(fragment)?.commit()
            } else {
                transaction?.show(fragment)?.commit()
            }
        }
    }

    private fun sendCall(it: Contact?) {
        /* val regitUrl = "http://139.196.195.193:8302/user_login"
         val login = Login()
         login.userPhone = "13821686815"
         login.userPassword = "123456"
         val gson = Gson()
         val json = gson.toJson(login)
         LogUtil.log("login:$json")
         HttpUtils.post(json, regitUrl, object : HttpUtils.HttpUtilsCallBack {
             override fun error(error: String) {
                 LogUtil.log("登录失败:$error")
                 //  showToast("登录失败:$error")
             }

             override fun successed(string: String) {
                 // {"returnCode":"1000","returnMessage":"注册成功"}
                 LogUtil.log("登录返回：$string")
                 // toMain(phone)
                 if ("success" == string) {
                     LogUtil.log("登录成功：$string")
                     //   showToast("登录成功")
                     //   toMain(phone)
                 } else {
                     //  showToast("登录失败")
                 }
             }
         })*/
        val pushUrl = "http://139.196.195.193:8302/msg_push"
        val msgPush = MsgPush()
        msgPush.recverPhoneNum = it?.contact_phone
        msgPush.senderPhoneNum = it?.phone
        msgPush.msgInfo = "01"
        msgPush.msgType = "12345678"
        msgPush.msgTime = DatesUtils.getNowTime("yyyyMMddHHmmss")
        msgPush.platform = 1;
        val gson = Gson()
        val json = gson.toJson(msgPush)
        //  val json = "{    \"senderPhoneNum\": \"13821686815\",    \"recverPhoneNum\": \"13590123974\",    \"msgInfo\":\"01\",    \"msgType\":\"12345678\",    \"msgTime\":\"24444444444444444\",    \"platform\":1}"
        LogUtil.log("msg_push:$json")
        HttpUtils.post(json, pushUrl, object : HttpUtils.HttpUtilsCallBack {
            override fun error(error: String) {
                LogUtil.log("推送失败:$error")
                Toast.makeText(this@HomeActivity, "推送失败:$error", Toast.LENGTH_SHORT).show()
            }

            override fun successed(string: String) {
                LogUtil.log("推送成功：$string")
                showVideoCallFragmentRoom(it?.contact_phone)
                if ("success" == string) {
                    Toast.makeText(this@HomeActivity, "推送成功：$string", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this@HomeActivity, "推送成功：$string", Toast.LENGTH_SHORT).show()
                }
            }
        })
    }

    private fun initListener() {
        //视频接听UI
        smoothLayout.setOnCallOperateListener(object : SmoothLayout.OnCallOperateListener {
            override fun onAnswer() {
                LogUtil.log("接听")
                smoothLayout.visibility = View.GONE
                vibrator?.cancel()
                showVideoCallFragmentRoom(phone)
            }

            override fun onHangup() {
                smoothLayout.visibility = View.GONE
                vibrator?.cancel();
                LogUtil.log("挂断")
            }
        })
        //进管理页
        llLogo.setOnClickListener {
            smoothLayout.visibility = View.VISIBLE
            val currentClickTime = SystemClock.uptimeMillis()
            val elapsedTime: Long = currentClickTime - mLastClickTime
            mLastClickTime = currentClickTime
            if (elapsedTime < MIN_CLICK_INTERVAL) {
                mSecretNumber++
                if (3 == mSecretNumber) {
                    showManagerDialog()
                }
            } else {
                mSecretNumber = 0
            }
        }
        adapter?.setCallListener {
            sendCall(it)
        }

        llAddCongtact.setOnClickListener {
            showAddContactDialog()
        }
        llmenu1.setOnClickListener {
            showMenuFragment()
        }

        llContext.setOnClickListener {
            ivContact1.visibility = View.VISIBLE
            ivHealth.visibility = View.GONE
            ivShopping2.visibility = View.GONE
            tvContact.isSelected = true
            ivContact.isSelected = true
            tvHealth.isSelected = false
            ivMenu.isSelected = false
            tvShopping.isSelected = false
            ivShopping.isSelected = false
            if (mContextFragment == null) {
                mContextFragment = ContextFragment()
            }
            showFragment(mContextFragment!!)
        }
        llShopping.setOnClickListener {
            ivContact1.visibility = View.GONE
            ivHealth.visibility = View.GONE
            ivShopping2.visibility = View.VISIBLE
            tvContact.isSelected = false
            ivContact.isSelected = false
            tvHealth.isSelected = false
            ivMenu.isSelected = false
            ivShopping.isSelected = true
            tvShopping.isSelected = true

            if (mShoppingFragment == null) {
                mShoppingFragment = ShoppingFragment()
            }
            showFragment(mShoppingFragment!!)
        }

        ivVoiceCallOff.setOnClickListener {
            val purchaseSP = getSharedPreferences("purchaseJson", Context.MODE_PRIVATE)
            //第一个参数是键名，第二个是默认值
            val purchaseData = purchaseSP?.getString("purchaseDate", "")
            Log.d("MenuFragment", "purchaseDate:$purchaseData")
            if (!purchaseData.isNullOrEmpty()) {
                val gson = Gson()
                val purchaseInfo = gson.fromJson(purchaseData, PurchaseInfo::class.java)
                val time1 = purchaseInfo.validity

                val currentThreadTimeMillis = System.currentTimeMillis()
                Log.d(
                    "MenuFragment",
                    "time1:$time1...currentThreadTimeMillis:$currentThreadTimeMillis"
                )
                if (time1 - currentThreadTimeMillis > 60000) {
                    /*if (mVideoCallFragment == null) {
                        mVideoCallFragment = VideoCallFragment()
                    }
                    showVideoCallFragment(mVideoCallFragment!!)*/
                } else {
                    if (mPurchaseFragment == null) {
                        mPurchaseFragment = PurchaseFragment()
                    }
                    showFragment(mPurchaseFragment!!)
                }
            } else {
                if (mPurchaseFragment == null) {
                    mPurchaseFragment = PurchaseFragment()
                }
                showFragment(mPurchaseFragment!!)
            }
        }

        if (mMenuFragment != null) {
            mMenuFragment?.setRegisteredListener(object : MenuFragment.RegisteredListener {
                override fun registered() {
                    if (mPurchaseFragment == null) {
                        mPurchaseFragment = PurchaseFragment()
                    }
                    showFragment(mPurchaseFragment!!)
                }
            })
        }

        if (mPurchaseFragment != null) {
            mPurchaseFragment?.setBuyListener(object : PurchaseFragment.BuyListener {
                override fun buyClick(data: PurchaseData?) {
//                    if (mMenuFragment == null) {
//                        mMenuFragment = MenuFragment()
//                    }
//                    showFragment(mMenuFragment!!)
                    showMenuFragment()
                }
            })
        }

        if (mShoppingFragment != null) {
            mShoppingFragment?.setBuyListener(object : ShoppingFragment.BuyListener {
                override fun buyClick(data: ShopData) {
                    if (mShoppingInfoFragment == null) {
                        mShoppingInfoFragment = ShoppingInfoFragment()
                    }
                    showFragment(mShoppingInfoFragment!!)
                }
            })
        }
        if (mShoppingInfoFragment != null) {
            mShoppingInfoFragment?.setSubmitListener(object : ShoppingInfoFragment.SubmitListener {
                override fun submitClick() {
                    if (mShoppingResultFragment == null) {
                        mShoppingResultFragment = ShoppingResultFragment()
                    }
                    showFragment(mShoppingResultFragment!!)
                }
            })
        }

        if (mShoppingResultFragment != null) {
            mShoppingResultFragment?.setBackHomeListener(object :
                ShoppingResultFragment.BackHomeListener {
                override fun backClick() {
                    showMenuFragment()
                }
            })
        }
    }

    private fun showVideoCallFragment(mVideoCallFragment: VideoCallFragment) {

        ivContact1.visibility = View.GONE
        ivHealth.visibility = View.GONE
        ivShopping2.visibility = View.GONE
        tvContact.isSelected = false
        ivContact.isSelected = false
        ivHealth.isSelected = false
        tvHealth.isSelected = false
        tvShopping.isSelected = false
        ivShopping.isSelected = false
        showFragment(mVideoCallFragment!!)
    }

    private fun replaceFragment(mPurchaseFragment: PurchaseFragment) {

    }

    public fun showMenuFragment() {
        val purchaseSP = getSharedPreferences("purchaseJson", Context.MODE_PRIVATE)
        //第一个参数是键名，第二个是默认值
        val purchaseData = purchaseSP?.getString("purchaseDate", "")
        LogUtil.log("purchaseDate:$purchaseData")
        if (!purchaseData.isNullOrEmpty()) {
            val gson = Gson()
            val purchaseInfo = gson.fromJson(purchaseData, PurchaseInfo::class.java)
            val time1 = purchaseInfo.validity
            phone = purchaseInfo.phone
            val currentThreadTimeMillis = System.currentTimeMillis()
            Log.d("MenuFragment", "time1:$time1...currentThreadTimeMillis:$currentThreadTimeMillis")
            if (time1 - currentThreadTimeMillis > 60000) {
                reclclerView.visibility = View.VISIBLE
                llAddCongtact.visibility = View.VISIBLE
                ivVoiceCallOff.visibility = View.GONE
                tvVoiceCall.visibility = View.GONE
                val sqLiteUtil = SQLiteUtil(this)
                contactList = sqLiteUtil.getContactList(phone)
                val layoutManager = LinearLayoutManager(this)
                layoutManager.orientation = LinearLayout.VERTICAL
                reclclerView.layoutManager = layoutManager as RecyclerView.LayoutManager?
                reclclerView.adapter = adapter
                adapter?.setData(contactList)
            } else {
                ivVoiceCallOff.visibility = View.VISIBLE
                reclclerView.visibility = View.GONE
                llAddCongtact.visibility = View.GONE
                ivVoiceCallOff.setImageResource(R.drawable.videocalloff)
                tvVoiceCall.visibility = View.VISIBLE
            }
        } else {
            llAddCongtact.visibility = View.GONE
            reclclerView.visibility = View.GONE
            ivVoiceCallOff.setImageResource(R.drawable.videocalloff)
            tvVoiceCall.visibility = View.VISIBLE
        }
        ivContact1.visibility = View.GONE
        ivHealth.visibility = View.VISIBLE
        ivShopping2.visibility = View.GONE
        ivContact.isSelected = false
        tvContact.isSelected = false
        tvHealth.isSelected = true
        ivMenu.isSelected = true
        ivShopping.isSelected = false
        tvShopping.isSelected = false

        if (mMenuFragment == null) {
            mMenuFragment = MenuFragment()
        }
        showFragment(mMenuFragment!!)
    }

    private fun requestPermissions() {

        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                val permission = ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(
                        this,
                        arrayOf(
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.LOCATION_HARDWARE,
                            Manifest.permission.READ_PHONE_STATE,
                            Manifest.permission.WRITE_SETTINGS,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.RECORD_AUDIO,
                            Manifest.permission.READ_CONTACTS
                        ),
                        0x0010
                    )
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun makeGattUpdateIntentFilter(): IntentFilter? {
        val intentFilter = IntentFilter()
        intentFilter.addAction(BluetoothService.ACTION_GATT_CONNECTED)
        intentFilter.addAction(BluetoothService.ACTION_GATT_DISCONNECTED)
        intentFilter.addAction(BluetoothService.ACTION_GATT_SERVICES_DISCOVERED)
        intentFilter.addAction(BluetoothService.ACTION_DATA_AVAILABLE)
        return intentFilter
    }

    override fun onResume() {
        super.onResume()
        isForeground = true
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter())
        address = SPUtils.getString(this@HomeActivity, SPUtils.ADDRESS, "")

        isBleUpdate = true
        Thread(Runnable {
            Log.e(TAG, "check BT")

            if (BtStatus.getText().toString() == "未连接") {
                progressBar!!.setVisibility(View.VISIBLE);
            }

            while (isBleUpdate) {

                try {
                    Thread.sleep(5000)
                } catch (e: InterruptedException) {
                    return@Runnable
                }

                if (BtStatus.getText().toString() == "未连接") {
                    if (!TextUtils.isEmpty(address)) {
                        mBluetoothLeService!!.connect(address)
                    }

                    try {
                        Thread.sleep(10000)
                    } catch (e: InterruptedException) {
                        return@Runnable
                    }

                } else {
                    //更新UI
                    oneButtonMeasurement(1)
                }
            }
        }).start()
    }

    override fun onDestroy() {
        super.onDestroy()
        isBleUpdate = false
        unbindService(mServiceConnection)
        unregisterReceiver(mGattUpdateReceiver)
    }

    override fun onPause() {
        super.onPause()
        isBleUpdate = false
        isForeground = false
    }

    // 初始化 JPush。如果已经初始化，但没有登录成功，则执行重新登录。
    private fun init() {
        JPushInterface.init(applicationContext)
    }

    fun registerMessageReceiver() {
        mMessageReceiver = MessageReceiver()
        val filter = IntentFilter()
        filter.priority = IntentFilter.SYSTEM_HIGH_PRIORITY
        filter.addAction(HomeActivity.MESSAGE_RECEIVED_ACTION)
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter)
    }

    inner class MessageReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            try {
                if (HomeActivity.MESSAGE_RECEIVED_ACTION == intent.action) {
                    val messge = intent.getStringExtra(HomeActivity.KEY_MESSAGE)
                    val extras = intent.getStringExtra(HomeActivity.KEY_EXTRAS)
                    val showMsg = StringBuilder()
                    showMsg.append(HomeActivity.KEY_MESSAGE + " : " + messge + "\n")
                    if (!ExampleUtil.isEmpty(extras)) {
                        showMsg.append(HomeActivity.KEY_EXTRAS + " : " + extras + "\n")
                    }
                    setCostomMsg(showMsg.toString())
                }
            } catch (e: java.lang.Exception) {
            }
        }
    }

    fun showVideoCallFragmentRoom(room: String?) {

        if (UCloudRtcSdkEnv.getSdkMode() == UCloudRtcSdkMode.UCLOUD_RTC_SDK_MODE_TRIVAL) {
            mRoomToken = "testoken"
        }
        val autoGenUserId = "android_" + UUID.randomUUID().toString().replace("-", "")
        mUserId =
            (if (MyAppliction.getUserId() != null) MyAppliction.getUserId() else autoGenUserId)!!
        mVideoCallFragment?.setData(mUserId, room, mRoomToken, mAppid)

        showVideoCallFragment(mVideoCallFragment!!)
    }

    private fun setCostomMsg(msg: String) {
        Log.d("接收到推送信息", msg)
        smoothLayout.visibility = View.VISIBLE
        // showVideoCallFragmentRoom(phone)
        //振动
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            vibrator!!.vibrate(
                VibrationEffect.createWaveform(
                    longArrayOf(
                        100L,
                        2000L,
                        1000L,
                        1000L,
                        3000L
                    ), 0
                )
            )
        } else {
            vibrator!!.vibrate(longArrayOf(100L, 2000L, 1000L, 1000L, 3000L), 0)
        }
        /*if (null != msgText) {
            msgText.setText(msg)
            msgText.setVisibility(View.VISIBLE)
        }*/
    }

    /**
     * 添加联系人。
     */
    private fun showAddContactDialog() {
        val dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_addcontact, null)
        addContactDialog = Dialog(this, R.style.dialog)
        dialogView.btnCancel.setOnClickListener {
            addContactDialog?.dismiss()

        }
        dialogView.btnConfirm.setOnClickListener {
            val etphone = dialogView.etAddContactPhone.text.toString().trim()
            val name = dialogView.etAddContactName.text.toString().trim()
            if (TextUtils.isEmpty(etphone)) {
                Toast.makeText(this, "请输入联系人电话号码", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(name)) {
                Toast.makeText(this, "请输入联系人姓名", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            var contact = Contact()
            contact.name = name
            contact.contact_phone = etphone
            contact.phone = phone
            val sqLiteUtil = SQLiteUtil(HomeActivity@ this)
            sqLiteUtil.insertContact(contact)
            contactList?.add(contact)
            adapter?.setData(contactList)
            addContactDialog?.dismiss()

        }
        addContactDialog?.setContentView(dialogView)
        addContactDialog?.setCanceledOnTouchOutside(false)
        val p = addContactDialog!!.window!!.attributes  //获取对话框当前的参数值// 获取屏幕宽、高用
        p.width = resources.getDimensionPixelOffset(R.dimen.dialog_width)
        p.height = resources.getDimensionPixelOffset(R.dimen.dialog_height)
        addContactDialog!!.window!!.attributes = p
        addContactDialog!!.show()
    }

    private fun showManagerDialog() {
        val view = View.inflate(this, R.layout.dialog_manager, null)
        val managerDialog = Dialog(this@HomeActivity, R.style.dialog)
        managerDialog.setContentView(view)
        val imageView: ImageView = view.findViewById<View>(R.id.close) as ImageView
        imageView.setOnClickListener(View.OnClickListener { managerDialog.dismiss() })
        val editText: LineEditText =  view.findViewById<View>(R.id.line_edit_text) as LineEditText
        val button: Button = view.findViewById<View>(R.id.btn_confirm) as Button
        button.setOnClickListener(View.OnClickListener {
            val password: String = editText.getText().toString().trim()
            if ("123456" == password) {
                managerDialog.dismiss()
                startActivity(Intent(this@HomeActivity,ManagerActivity::class.java))
            } else {
                Toast.makeText(this@HomeActivity, "您输入的密码有误,请重新输入", Toast.LENGTH_SHORT).show()
            }
        })
        val p =  managerDialog.window.attributes //获取对话框当前的参数值// 获取屏幕宽、高用
        p.width = resources.getDimensionPixelOffset(R.dimen.dialog_width)
        p.height = resources.getDimensionPixelOffset(R.dimen.dialog_height)
        managerDialog.setCancelable(false)
        managerDialog.window.attributes = p
        managerDialog.setCanceledOnTouchOutside(false) // 设置点击屏幕Dialog消失
        managerDialog.show()
    }
}
